# -*-coding:utf-8-*-
"""
@project: SM
@Time: 2024-08-01 19:52
@Author: Loneliness_Burial
@File: src.py.py
@Motto: 深情不改必坠死海
@software: pycharm
@version: python 3.7
"""

import re
from interface import user_interface, bank_interface, shop_interface
from lib import common
from core import Admin

"""
用户视图层
"""

logged_user = None
logged_admin = False


# 0.退出
def sign_out():
    print('\n感谢使用,欢迎下次光临！')
    exit()


# 1.注册功能
def register(is_admin=False):
    while True:
        print('\n注册')
        username = input('请输入用户名：').strip()
        password = input('请输入密码：').strip()
        re_password = input('请确认密码：').strip()
        is_register = input('按任意键确认/n退出:').strip().lower()
        if is_register == 'n':
            break
        if password != re_password:
            print('\n两次输入的密码不一致! ')
            continue
        # 用户名必须有字母数字下划线组成，必须由字母开头   正则：字母开头[],a-zA-Z字母a-z,\w下划线,{2,9}用户名在3个字符-10个字符之间
        if not re.findall('^[a-zA-Z]\w{2,9}$', username):
            print('\n用户名长度必须为3-10个字符! \n只能由字母、数字、下划线组成,并只能以字母开头！')
            continue
        # 校验密码，密码必须包含大小写字母及数字
        if not re.findall('^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,16}$', password):
            print('\n密码太弱, 必须包含大写字母、小写字母、数字, 并且长度必须为8-16位! ')
            continue
        password = common.pwd_to_sha256(password)
        flag, msg = user_interface.register_interface(username, password, is_admin)
        print(msg)
        if flag:
            break


# 2.登录功能

def login():
    while True:
        print('\n登录')
        username = input('\n请输入用户名: ').strip()
        password = input('\n请输入密码: ').strip()
        is_login = input('按任意键确认/n退出: ').strip().lower()
        if is_login == 'n':
            break
        password = common.pwd_to_sha256(password)
        flag, msg, is_admin = user_interface.login_interface(username, password)
        print(msg)
        if flag:
            global logged_user, logged_admin
            logged_user = username
            logged_admin = is_admin
            break


# 3.充值功能
@common.login_auth
def recharge(username=False):
    while True:
        print('\n充值')
        amount = input('请输入充值金额：').strip()
        is_recharge = input('按任意键确认/n退出: ').strip().lower()
        if is_recharge == 'n':
            break
        if not amount.isdigit():
            print('\n请输入正确的金额! ')
            continue
        amount = int(amount)
        if amount == 0:
            print('\n充值的金额不能为0! ')
            continue
        if not username:
            username = logged_user
        flag, msg = bank_interface.recharge_interface(username, amount)
        print(msg)
        if flag:
            break


# 4.转账功能
@common.login_auth
def transfer():
    while True:
        print('\n转账')
        to_username = input('请输入转账目标的用户名：').strip()
        amount = input('请输入转账的金额：').strip()
        is_transfer = input('按任意键确认/n退出: ').strip().lower()
        if is_transfer == 'n':
            break
        if not amount.isdigit():
            print('\n请输入正确的金额! ')
            continue
        amount = int(amount)
        if amount == 0:
            print('\n转账的金额不能为0! ')
            continue
        if logged_user == to_username:
            print('\n不能给自己转账! ')
            continue
        flag, msg = bank_interface.transfer_interface(
            logged_user, to_username, amount
        )
        print(msg)
        if flag:
            break


# 5.提现功能
@common.login_auth
def withdraw():
    while True:
        print('\n提现')
        amount = input('请输入提现金额：').strip()
        is_withdraw = input('按任意键确认/n退出: ').strip().lower()
        if is_withdraw == 'n':
            break
        if not amount.isdigit():
            print('\n请输入正确的金额! ')
            continue
        amount = int(amount)
        if amount < 500:
            print('\n提现的金额不能低于500! ')
            continue
        flag, msg = bank_interface.withdraw_interface(logged_user, amount)
        print(msg)
        if flag:
            break


# 6.查看余额
@common.login_auth
def check_balance():
    print('\n查看余额')
    flag, msg = bank_interface.check_balance_interface(logged_user)
    print(msg)


# 7.查看流水
@common.login_auth
def check_flow():
    print('\n您当前的流水记录为: ')
    flag, flow_list = bank_interface.check_flow_interface(logged_user)
    if not flow_list:
        print('\n当前用户没有流水! ')
    for flow in flow_list:
        print(flow)


# 8.购物功能
@common.login_auth
def shopping():
    shopping_cart = {}
    goods = shop_interface.check_goods_interface('goods')
    if not goods:
        print('\n没有商品数据! ! ! ')
        return
    while True:
        print('\n欢迎来到铁牛商城'.center(50, '='))
        print(f'{"序号":<10}{"商品编号":<10}{"商品名称":<10}{"商品价格":<10}')
        for indx, good in enumerate(goods):
            print(f'{indx + 1:<10}{good.get("number"):<10}{good.get("name"):<10}{good.get("price"):<10}')
        print('\n24小时为您服务'.center(50, '='))
        opt = input('请选择商品序号(y结算/n退出)：').strip()
        if opt == 'n':
            if not shopping_cart:
                break
            flag, msg = shop_interface.add_shop_cart_interface(logged_user, shopping_cart)
            print(msg)
            if flag:
                break
        if opt == 'y':
            if not shopping_cart:
                print(f'\n没有选择任何商品，无法计算! ')
                continue
            flag, msg, total = shop_interface.close_account_interface(logged_user, shopping_cart)
            print(msg)
            if flag:
                print('欢迎光临铁牛商城'.center(65, ' '))
                print('=' * 65)
                print(
                    f'{"序号":<10}{"商品编号":<10}{"商品名称":<10}{"商品价格":<10}{"商品价格":<10}{"商品数量":<10}{"商品总价":<10}')
                for indx, good in enumerate(shopping_cart.values()):
                    print(
                        f'{indx + 1:<10}{good.get("number"):<10}{good.get("name"):<10}{good.get("price"):<10}{good.get("数量"):<10}{good.get("数量") * good.get("price"):<10}')
                print(f'总消费金额: {total} ')
                print('=' * 65)
                print('谢谢惠顾，欢迎下次光临! ! ! '.center(65, ' '))
                print('请保管好您的小票! ! ! '.center(65, ' '))
            break
        if not opt.isdigit():
            print('\n请输入正确的商品编号! ')
            continue
        opt = int(opt) - 1
        if opt not in list(range(len(goods))):
            print('\n该商品不存在! ')
            continue
        good_info = goods[opt]
        name = good_info.get('name')
        if name not in shopping_cart:
            good_info['数量'] = 1
            shopping_cart[name] = good_info
        else:
            shopping_cart[name]['数量'] += 1
        print('\n当前购物车数据: ')
        print(
            f'{"序号":<10}{"商品编号":<10}{"商品名称":<10}{"商品价格":<10}{"商品价格":<10}{"商品数量":<10}{"商品总价":<10}')
        for indx, good in enumerate(shopping_cart.values()):
            print(
                f'{indx + 1:<10}{good.get("number"):<10}{good.get("name"):<10}{good.get("price"):<10}{good.get("数量"):<10}{good.get("数量") * good.get("price"):<10}')


# 9.查看购物车
@common.login_auth
def check_shopping_cart():
    # print('查看购物车')
    shop_cart_file = shop_interface.check_shop_cart_interface(logged_user)
    if not shop_cart_file:
        print('\n购物车空空如也! ! !')
        return
    print('\n当前购物车数据: ')
    print(
        f'{"序号":<10}{"商品编号":<10}{"商品名称":<10}{"商品价格":<10}{"商品价格":<10}{"商品数量":<10}{"商品总价":<10}')
    for indx, good in enumerate(shop_cart_file.values()):
        print(
            f'{indx + 1:<10}{good.get("number"):<10}{good.get("name"):<10}{good.get("price"):<10}{good.get("数量"):<10}{good.get("数量") * good.get("price"):<10}')
    opt = input('y付款/n退出').strip().lower()
    if opt == 'y':
        flag, msg, total = shop_interface.close_account_interface(logged_user, shop_cart_file)
        print(msg)
        if flag:
            shop_interface.clear_shop_cart_interface(logged_user)


# 10.退出账号
@common.login_auth
def login_out():
    print('\n退出账号')
    global logged_user, logged_admin
    print(f'\n用户: {logged_user} 已退出！')
    logged_user = None
    logged_admin = False


# 11.管理员功能
@common.login_auth
def admin():
    print("尊敬的管理员，您好！！！")
    Admin.main()


# 函数字典
func_dic = {
    '0': ('退出', sign_out),
    '1': ('注册功能', register),
    '2': ('登录功能', login),
    '3': ('充值功能', recharge),
    '4': ('转账功能', transfer),
    '5': ('提现功能', withdraw),
    '6': ('查看余额', check_balance),
    '7': ('查看流水', check_flow),
    '8': ('购物功能', shopping),
    '9': ('查看购物车', check_shopping_cart),
    '10': ('退出功能', login_out),
    '11': ('管理员功能', admin),
}


# 主程序
def main():
    while True:
        print("购物管理系统".center(20, '='))
        for num in func_dic:
            if logged_admin:
                print(f'{num} {func_dic.get(num)[0]}'.center(20, ' '))
            else:
                if num != '11':
                    print(f'{num} {func_dic.get(num)[0]}'.center(20, ' '))
        print("我也是有底线的".center(20, '='))
        opt = input('请输入功能编号:').strip()
        if opt not in func_dic or (not logged_admin and opt == '11'):
            print('此功能不存在！')
            continue
        func_dic.get(opt)[1]()
